const mongoose = require("mongoose");
const { MongodbConfig } = require("../libs/config");

let isReconnect = false;
let connectStr = "mongodb://";

// 拼接connectStr
if (MongodbConfig.replication) {
  if (MongodbConfig.user) {
    connectStr += `${connectStr + MongodbConfig.user}:${MongodbConfig.pwd}@`;
  }
  MongodbConfig.servers.forEach((server) => {
    connectStr += `${server.host}:${server.port},`;
  });
  connectStr = connectStr.substring(0, connectStr.length - 1);
  connectStr += `/${MongodbConfig.db}?replicaSet=${MongodbConfig.replication}`;
} else {
  if (MongodbConfig.user) {
    connectStr += `${MongodbConfig.user}:${MongodbConfig.pwd}@${MongodbConfig.host}:${MongodbConfig.port}/${MongodbConfig.db}`;
  } else {
    connectStr += `${MongodbConfig.host}:${MongodbConfig.port}/${MongodbConfig.db}`;
  }
}

if (MongodbConfig.authSource) {
  connectStr += `&authSource=${MongodbConfig.authSource}`;
}

function connectdb(times) {
  isReconnect = true;
  mongoose.connect(
    connectStr,
    { useNewUrlParser: true, useUnifiedTopology: true },
    (err) => {
      if (err) {
        console.error("mongodb连接失败!");
        console.error(connectStr);
        if (times < 1000) {
          setTimeout(() => {
            connectdb(++times);
          }, 1000);
        } else {
          throw new Error("重试连接mongodb失败，请检查配置");
        }
      } else {
        console.log("mongodb连接成功。");
        isReconnect = false;
        const conn = mongoose.connection;
        conn.on("disconnected", () => {
          console.error("mongodb连接断开,重试中……\t");
          if (!isReconnect) {
            connectdb(1);
          }
        });
        conn.on("error", (e) => {
          console.error(`mongodb连接失败:\n${e.stack}` || e);
          if (!isReconnect) {
            connectdb(1);
          }
        });
      }
    }
  );
}

connectdb(1);

module.exports = { MongooseClient: mongoose };
